package com.roosterrobotics.replicant;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

import com.roosterrobotics.replicant.R;

import com.roosterrobotics.replicant.provider.ReplicantData;

import android.app.Activity;
import android.content.ContentProvider;
import android.content.ContentProviderClient;
import android.content.res.Resources;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;




public class ActuatorDetail extends Activity {

	private TextView mActuatorName;
	private TextView mMinimumValue;
	private TextView mMaximumValue;
	private SeekBar mValueBar;

	private Button mSendButton;

	private ContentProviderClient client;
	private ContentProvider provider;
	private String address;
	private Long port;
	private Long mActuatorId;
	private Long mMinValue;
	private Long mMaxValue;
	private String commName;
	private String devName;
	
	private static final String REPSETACTUATOR = "RepSetActuator";
	private static final String REPSETFEEDBACKACTUATOR = "RepSetFeedbackActuator";
	private static final String EOM = "#";
	
	
	 @Override
	    public void onCreate(Bundle savedInstanceState) {
		 super.onCreate(savedInstanceState);
			
			Resources res = getResources();
		    client = getContentResolver().acquireContentProviderClient(ReplicantData.AUTHORITY);
		    provider = client.getLocalContentProvider();
			setContentView(R.layout.actuator_detail);
			setTitle(R.string.actuator_detail);
			
			mActuatorName = (TextView) findViewById(R.id.actuatorName);
			mMinimumValue = (TextView) findViewById(R.id.minimumValue);
			mMaximumValue = (TextView) findViewById(R.id.maximumValue);
			
			mValueBar = (SeekBar) findViewById(R.id.valueBar);
			
			
			mSendButton = (Button) findViewById(R.id.actuatorButton);

			
			Bundle extras = getIntent().getExtras();
			
			if (extras != null) {
				mActuatorId = extras.getLong(ReplicantData.Actuators.ACTUATOR_INTERNAL_ID_COLUMN_NAME);
				mActuatorName.setText(extras.getString(ReplicantData.Actuators.ACTUATOR_NAME_COLUMN_NAME));
				mMinValue = extras.getLong(ReplicantData.Actuators.ACTUATOR_MINVALUE);
				mMinimumValue.setText(String.valueOf(mMinValue));
				mMaxValue = extras.getLong(ReplicantData.Actuators.ACTUATOR_MAXVALUE);
				mMaximumValue.setText(String.valueOf(mMaxValue));
				
				mValueBar.setMax(mMaxValue.intValue());
				commName = extras.getString("CommunityName");
				devName = extras.getString("DeviceName");
				address = extras.getString(ReplicantData.Devices.DEVICE_ADDRESS_COLUMN_NAME);
				port = extras.getLong(ReplicantData.Devices.DEVICE_PORT_COLUMN_NAME);
			}
			
			mSendButton.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					new ActuatorNetworkMessenger(REPSETACTUATOR).execute(address, String.valueOf(port), REPSETACTUATOR + 
							" " + commName + " " + devName + 
							" myApp "  +  mActuatorId + " " + mValueBar.getProgress() + EOM);
				}
			});
	 }
	 
	 
		private class ActuatorNetworkMessenger extends AsyncTask<String, Void, String> {
			PrintWriter out = null;
			BufferedReader in = null;
			Socket s = null;
			String msg;
			
			public ActuatorNetworkMessenger(String m) {
				super();
				msg = m;
			}
			
			protected String doInBackground(String...strings) {
				String buffer = "";
				char a;

				try {
					s = new Socket(strings[0], Long.decode(strings[1]).intValue());
					out = new PrintWriter(s.getOutputStream());
					in = new BufferedReader(new InputStreamReader(s.getInputStream()));
					
					while (in.ready()) {
						a  = (char) in.read();
					}	
					msg = strings[2];
					out.println(msg);
					out.flush();
					buffer = in.readLine();
					out.close();
					in.close();
					s.close();
					// If there isn't a response but the connection was established.
					if (buffer == null) {
						buffer = "Error: Device not responding";
					}
				} catch (NumberFormatException e) {
					buffer = "Exception: Address format incorrect";
					return buffer;
				} catch (UnknownHostException e) {
					buffer = "Exception: Unknown host";
					return buffer;
				} catch (IOException e) {
					buffer = "Exception: I/O Error";
					return buffer;
				}
				return buffer;
			}
			
			@Override
			protected void onPreExecute() {
				super.onPreExecute();

				
			}
			
			@Override
			protected void onPostExecute(String result) {
				super.onPostExecute(result);
				if (result.startsWith("Error:") || result.startsWith("Exception:")) {
					Toast toast = Toast.makeText(ActuatorDetail.this, result, Toast.LENGTH_LONG);
					toast.show();
				}
			}
		}
}
